package md.NJavaUmeng;

import android.Manifest;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
//import android.support.v4.app.ActivityCompat;
//import android.support.v4.content.ContextCompat;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.util.Log;
import android.util.Pair;

import com.alibaba.fastjson.JSONObject;

import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.commonsdk.statistics.common.DeviceConfig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import md.NJavaBase.Debug;
import md.NJavaBase.IActivityOverride;
import md.NJavaBase.ICallbackQWEvent;
import md.NJavaBase.NJavaBase;
import md.NJavaBase.QWEvent;

//需要 androidX
//compile group: 'com.alibaba', name: 'fastjson', version: '1.2.47'
//依赖 implementation 'com.android.support:support-v4:23.4.0'
//implementation 'com.android.support:appcompat-v7:24.2.1'
public class Umeng {
    static String Tag = "Umeng";
    static String g_Channel = "";
    public  static String getChannel(){ return  g_Channel; }

    public static void Go()
    {
        Log.d(Tag, "Go#1");

        if(Build.VERSION.SDK_INT >= 23)//构建版本大于等于23
        {
            //监听授权结果
            NJavaBase.addEventListener(
                    NJavaBase.EVT_REQUEST_PERMISSIONS_RESULT,
                    new ICallbackQWEvent(){
                        @Override
                        public void reCall(QWEvent evt)
                        {
                            int code = (int)evt.Details;
                            if(code==REQUEST_READ_PHONE_CODE)
                            {
                                Log.d(Tag, "auth #1");
                                DoInit();
                            }
                        }
                  }
            );


            //请求权限
            Activity activity = NJavaBase.getActivity();

            //请求权限
            int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE);

            if (permissionCheck != PackageManager.PERMISSION_GRANTED)//当前没有获得权限
            {
                Log.d(Tag, "auth #0");
                //请求权限
                ActivityCompat.requestPermissions(
                        activity,
                        new String[]{Manifest.permission.READ_PHONE_STATE},
                        REQUEST_READ_PHONE_CODE
                );
            }
            else {
                Log.d(Tag, "auth #2");
                DoInit();
            }

        }else {
            Log.d(Tag, "auth #3");
            DoInit();
        }

    }
    public static final int REQUEST_READ_PHONE_CODE = 1;


    public static String UmengAppid = "";

    static void DoInit()
    {
        NJavaBase.addActivityOverride(new IActivityOverride() {
            @Override
            public void onResume() {
                Log.d(Tag, "onResume Begin");
                MobclickAgent.onResume(NJavaBase.getActivity());
                Log.d(Tag, "onResume End");
            }

            @Override
            public void onPause() {
                Log.d(Tag, "onPause Begin");
                MobclickAgent.onPause(NJavaBase.getActivity());
                Log.d(Tag, "onPause End");
            }

            @Override
            public void onDestroy() {

            }
        }); 

        Activity activity = NJavaBase.getActivity();

        //读取参数
        try {
            ApplicationInfo appInfo = activity.getPackageManager().getApplicationInfo(
                    activity.getPackageName(), PackageManager.GET_META_DATA
            );

            UmengAppid = appInfo.metaData.getString("UmengAppid")  ;
            g_Channel= appInfo.metaData.getString("UmengChannel")  ;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(Tag, "Go error!");
            e.printStackTrace();
        }

        if(Debug.ENABLE) {
            UMConfigure.setLogEnabled(true);

            try {

                String device_id = String.format( "{\"device_id\":\"%s\",\"mac\":\"%s\"}",
                        DeviceConfig.getDeviceIdForGeneral(activity),
                        DeviceConfig.getMac(activity)
                );

                Log.d(Tag,"设备标识符:"+device_id);

            } catch (Exception e){
                Log.e(Tag,"获取设备标识符异常");
            }

        }else
            UMConfigure.setLogEnabled(false);

        // 初始化SDK
        UMConfigure.init(
                activity,
                UmengAppid,
                g_Channel,
                UMConfigure.DEVICE_TYPE_PHONE,
                null//push推送的secret
        );

        // 选用MANUAL页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.MANUAL);

        g_initd = true;
        Log.d(Tag, "init end appKey "+UmengAppid);

        //立即发送所有缓存的事件
        for(int i=0;i<g_EventList.size();i++)
        {
            Pair<String,Map<String, Object>> curr = (Pair<String,Map<String, Object>>)g_EventList.get(i);
            trackEvent(curr.first, curr.second);
        }
        g_EventList.clear();
        trackEvent("uminit", new HashMap<String, Object>( ) );
    }

    public static void trackEvent(String evtName, Map<String, Object> evtParams)
    {
        Log.d(Tag,"trackEvent "+evtName);
        if(!g_initd)//尚未初始化
        {
            //缓存事件
            g_EventList.add(  new Pair<>(evtName,evtParams) );
            return;
        }

        if(evtParams.size()!=0)
            MobclickAgent.onEventObject(NJavaBase.getActivity(),evtName,evtParams);
        else
            MobclickAgent.onEvent(NJavaBase.getActivity(),evtName);
    }

    public static void trackEventJson(String evtName, String params) {
        Log.d(Tag,evtName);
        Map stringToMap =  JSONObject.parseObject(params);
        trackEvent(  evtName, stringToMap);
    }

    static ArrayList g_EventList = new ArrayList();//缓存的事件列表
    static boolean g_initd = false;//是否已经初始化
}
